from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.ext import db
import os, tables

from html import CheckBox, DropDown #importing the html wrappers
from tables import Ta, Section
import validate #import validation
import cgi #for escaping html chars in forms

class QuickSearch(webapp.RequestHandler):
    '''Class to simulate a quicksearch'''
    def __init__(self):
        webapp.RequestHandler.__init__(self) #calling parent constructor
        self.currentState = tables.AppState.get_by_key_name('currentState')
        self.currentSemester = self.currentState.semester
        
        self.semesters = dict()
        for semester in db.GqlQuery("SELECT * FROM Semester"): self.semesters[str(semester)] = semester        

    
    def get(self):
        '''Executed when visited from URL'''
        self.searchSemester = self.currentSemester
        self.renderTemplate()
        
    def post(self):
        if self.request.get('searchFor') == 'tas':
            ta = True
        else:
            ta = False
        searchString = cgi.escape(self.request.get('searchString'))
        #searchString = self.request.get('searchString')
        searchFor = self.request.get('searchFor')
        validSearch = validate.quickSearch(searchString, searchFor)
        self.searchSemester = self.semesters[self.request.get('semesters')]
        results = []
        if ta:
            tas = db.GqlQuery("SELECT * FROM Ta")
            #tas = Ta.all().search(searchString)
            for r in tas:
                if not r.submitted:
                    continue
                if str(r.semester) != str(self.searchSemester):
                    continue
                bigString = "" + '\n' + str(r.firstName) + '\n' + str(r.lastName) + '\n' + str(r.phone) + '\n' + str(r.email) + '\n' + str(r.major.name) + '\n' + str(r.degree) + '\n' + str(r.supervisor) + '\n' + str(r.semester.season.name) + '\n' + str(r.semester.year) + '\n' + str(r.eid)
                for x in r.taQualifications:
                    bigString += '\n' + str(x.qualification.identifier) + '\n' + str(x.qualification.name)
                for x in r.taSpecializations:
                    bigString += '\n' + str(x.specialization.name)
                for x in r.taLanguages:
                    bigString += '\n' + str(x.language.name)
                for x in r.taTaHistory:
                    bigString += '\n' + str(x.taHistory.identifier) + '\n' + str(x.taHistory.name)
                #self.response.out.write(r.firstName)
                #if str(r.firstName) == 'Steven': print bigString
                searchArray = searchString.lower().split()
                bigString = bigString.lower()
                flag = True
                for x in searchArray:
                    if bigString.find(x)==-1:
                        flag = False
                        break
                if flag:
                    results.append(r)
        else:
            #sections = Section.all().search(searchString)
            sections = db.GqlQuery("SELECT * FROM Section")
            for r in sections:
                if str(r.semester) != str(self.currentSemester):
                    continue
                bigString = "" + str(r.uniqueNumber) + '\n' + str(r.course.identifier) + '\n' + str(r.course.name) + '\n' + str(r.instructor.firstName) + '\n' + str(r.instructor.lastName) + '\n' + str(r.numTas) + '\n' + str(r.numStudents) + '\n' + str(r.semester.season.name) + '\n' + str(r.semester.year)
                for x in r.taSections:
                    bigString += '\n' + x.ta.firstName + '\n' + x.ta.lastName + '\n' + x.ta.eid
                searchArray = searchString.lower().split()
                bigString = bigString.lower()
                flag = True
                for x in searchArray:
                    if bigString.find(x)==-1:
                        flag = False
                        break
                if flag:
                    results.append(r)
        '''Validates and parses template after form submission'''

        self.renderTemplate(searchString,searchFor, validSearch, True,ta,results)
        
    def renderTemplate(self,searchString = None, searchFor=None, validSearch=False, posted=False, ta = None, results = None) :
        '''Renders template file quickSearch.html'''
        
        
        #setting up template dictionary
        templateValues = {
            'ta': ta,
            'results': results,
            'empty': results is None or len(results) == 0,
            'searchString': searchString,
            'validSearch': validSearch,
            'searchFor': searchFor,
            'posted': posted, 
            'searchSemester': self.searchSemester,
            'semesters': DropDown(options=self.semesters.keys(), name = "semesters", selected = str(self.searchSemester), defaultOptionPresent = False), #for choosing 'view'
        }
        
        #telling it to use the template
        path = os.path.join(os.path.dirname(__file__), 'quickSearch.html')
        self.response.out.write(template.render(path, templateValues))
 
application = webapp.WSGIApplication([('/admin/quickSearch', QuickSearch)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
